package com.test.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.web.pojo.User;
import com.test.web.service.UserService;
import com.test.web.service.impl.UserServiceImpl;

import jxl.Workbook;
import jxl.format.Border;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * Servlet implementation class ExcelExportServlet
 */
public class ExcelExportServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String("用户".getBytes("GB2312"), "8859_1") + ".xls");
		response.setHeader("pragma", "no-cache");
		response.setContentType("application/msexcel");// 定义输出类型
		ServletOutputStream os = response.getOutputStream();
		
		UserService userService = new UserServiceImpl();
		List<User> list = userService.all();

		if (list == null) {
			return;
		}
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			WritableSheet ws = workbook.createSheet("用户列表", 0);
			
			int rowNum = 0;

			WritableFont font1 = new WritableFont(WritableFont.TIMES, 16,
					WritableFont.BOLD);
			WritableCellFormat format1 = new WritableCellFormat(font1);
			Label cell = new Label(0, 0, "导出用户列表", format1);
			ws.addCell(cell);
			
			WritableCellFormat cellFormat2 = new WritableCellFormat(); 
			cellFormat2.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN); 
			
			ws.setColumnView(300, 200);
			
			rowNum = 1;
			for (int i = 0; i < list.size(); i++, rowNum++) {// 写sheet
				User tmp = list.get(i);

				ws.addCell(new Label(0, rowNum, tmp.getName() + "", cellFormat2));
				ws.addCell(new Label(1, rowNum, tmp.getAge().toString(), cellFormat2));
				ws.addCell(new Label(2, rowNum,
						Integer.valueOf(1).equals(tmp.getChoosed()) ? "管理员" : "普通用户", cellFormat2));
				ws.addCell(new Label(3, rowNum, tmp.getAddress(), cellFormat2));
			}
			workbook.write();
			workbook.close();
		} catch (RowsExceededException e) {
			throw new RuntimeException(e);
		} catch (WriteException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		os.close();
	}

}
